﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using LiveProjectManager.DDD;


namespace LiveProjectManager.Controllers
{
    public class CategoryController : Controller
    {
        private static DDD.Services.CategoryService _service = new DDD.Services.CategoryService();


        //
        // GET: /Category
        public ActionResult Index(int paginateBy = 0, int page = 1)
        {
            return Json(
                DDD.Services.CategoryService.toDict(_service.getAll(paginateBy, page)), 
                JsonRequestBehavior.AllowGet
            );
        }


        //
        // GET: /Category/Details/{Id}
        public ActionResult Details(long id)
        {
            DDD.Domains.Category myCategory = _service.getById(id);

            // Can't find a matching resource.
            if (myCategory == null)
                return new HttpStatusCodeResult((int)HttpStatusCode.NotFound);

            // Return formatted resource.
            return Json(myCategory.toDict(), JsonRequestBehavior.AllowGet);
        }


        //
        // POST: /Category/Create
        [HttpPost]
        public ActionResult Create(FormCollection myFormData)
        {
            // If we can't create a category, one of the parameters must be invalid.
            if (!_service.create(myFormData["Name"], myFormData["Description"]))
                return new HttpStatusCodeResult((int)HttpStatusCode.BadRequest);
            return new HttpStatusCodeResult((int)HttpStatusCode.Created);
        }


        //
        // DELETE: /Category/Delete
        [HttpDelete]
        public ActionResult Delete(FormCollection myFormCollection)
        {
            try
            {
                // Entity to delete is not found.
                if (!_service.exists(long.Parse(myFormCollection["Id"])))
                    return new HttpStatusCodeResult((int)HttpStatusCode.NotFound);

                // Unknown error occured, unable to delete.
                if (!_service.remove(long.Parse(myFormCollection["Id"])))
                    return new HttpStatusCodeResult((int)HttpStatusCode.InternalServerError);

                // Deletion successful
                return new HttpStatusCodeResult((int)HttpStatusCode.NoContent);
            }
            catch (Exception)
            {
                return new HttpStatusCodeResult((int)HttpStatusCode.BadRequest, "Invalid Id parameter (must be a long).");
            }
        }
    }
}
